/**
 * 
 */
package com.lazyshopkeeper.front.interceptor;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.lazyshopkeeper.front.api.OAuthTaobaoClient;
import com.lazyshopkeeper.front.common.Constant;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.User;
import com.taobao.api.internal.util.StringUtils;
import com.taobao.api.internal.util.TaobaoUtils;
import com.taobao.api.internal.util.WebUtils;
import com.taobao.api.request.UserSellerGetRequest;
import com.taobao.api.response.UserSellerGetResponse;

/**
 * @author Yockii
 *
 */
public class OAuthInterceptor extends HandlerInterceptorAdapter {
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		String error = request.getParameter("error");
		if(!StringUtils.isEmpty(error) && "access_denied".equalsIgnoreCase(error)){
			// error_description = authorize%20reject
			return false;
		}
		
		String code = request.getParameter("code");
		if(!StringUtils.isEmpty(code)){
			// taobao_user_nick  taobao_user_id  sub_taobao_user_id  sub_taobao_user_nick r1_expires_in r2_expires_in w1_expires_in w2_expires_in
			// w2_expires_in refresh_token expires_in  token_type  access_token
			
			Map<String, String> params = new HashMap<String, String>();
			params.put("client_id", Constant.APP_KEY);
			params.put("client_secret", Constant.APP_SERCET);
			params.put("grant_type", "authorization_code");
			params.put("code", code);
			params.put("redirect_uri", request.getRequestURL().toString());
			String responseJson = WebUtils.doPost(Constant.OAUTH_URL, params, 3000, 3000);
			Map result = TaobaoUtils.parseJson(responseJson);
			String token = (String) result.get("access_token");
			
			TaobaoClient client = new OAuthTaobaoClient(token);
			// 根据获取的token取得用户信息
			UserSellerGetRequest ugReq = new UserSellerGetRequest();
			ugReq.setFields("nick,sex,seller_credit");
			
			UserSellerGetResponse ugRes = client.execute(ugReq);
			User user = ugRes.getUser();
		}
		return super.preHandle(request, response, handler);
	}


}
